<template>
  <div class="app-container">
    <!-- 选择数字员工 -->
    <el-row :gutter="20">
      <el-col :span="8">
        <span style="padding-right: 10px">内容创作数字员工</span>
        <el-select v-model="selectedEmployee" placeholder="请选择">
          <el-option
            v-for="item in employees"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="8">
        <span style="padding-right: 10px">网页设计数字员工</span>
        <el-select v-model="designerEmployee" placeholder="请选择">
          <el-option
            v-for="item in employees"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="8">
        <el-button type="primary" @click="generateContent" :loading="loading">生成</el-button>
      </el-col>
    </el-row>

    <!-- 输入需要生成文章的提示词 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <el-input
          type="textarea"
          :rows="3"
          placeholder="请输入需要生成文章的提示词"
          v-model="prompt">
        </el-input>
      </el-col>
    </el-row>

    <!-- 生成的文案和预览效果 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <div class="generated-content">
          <h4>生成的文案</h4>
          <v-md-editor v-model="generatedText" height="500px"></v-md-editor>
        </div>
      </el-col>
    </el-row>

    <!-- 保存和取消按钮 -->
    <el-row :gutter="20" style="margin-top: 20px; text-align: right;">
      <el-button type="success" @click="saveContent">保存</el-button>
      <el-button @click="cancel">取消</el-button>
    </el-row>
  </div>
</template>

<script>
import { sseRequest } from '@/utils/sseRequest'
import {chat, saveContentToServer} from '@/api/system/chat';
import { listEmployee } from "@/api/system/employee";
import designer from "@/components/Process/designer.vue";
export default {
  computed: {
    filteredEmployees() {
      return this.employees.filter(item =>
        item.value !== this.selectedEmployee &&
        item.value !== this.designerEmployee
      );
    },
    designer() {
      return designer
    }
  },
  data() {
    return {
      selectedEmployee: '',
      designerEmployee: '',
      employees: [
        { value: '1', label: '员工1' },
        { value: '2', label: '员工2' },
        // 更多员工...
      ],
      prompt: '小户型装修避坑指南',
      generatedText: '',
      previewHtml: '',
      messages: [],
      loading: false,
      eventSource: null
    };
  },
  mounted() {
    this.listEmployees();
  },
  beforeDestroy() {

  },
  methods: {
    connectSSE() {
      // this.eventSource = sseRequest.create({
      //   url: '/ai/content/generate',
      //   onMessage: (data) => {
      //     this.messages.push(data)
      //   },
      //   onError: (error) => {
      //     console.error('SSE错误:', error)
      //     setTimeout(() => this.connectSSE(), 1000)
      //   }
      // })
    },

    listEmployees() {
      listEmployee({
        pageNum: 1,
        pageSize: 100
      }).then(response => {
        console.log(response)
        this.employees = response.rows.map(item => ({
          value: item.id,
          label: item.name
        }));
        // this.selectedEmployee = this.em
      })

    },
    generateContent() {
      // 清空之前的内容
      this.generatedText = ''
      this.previewHtml = ''
      this.messages = []
      this.loading = true;
      let data = {
        employeeId: this.selectedEmployee,
        prompt: this.prompt
      }
      sseRequest.create({
        url: '/ai/content/stream',
        method: 'POST',
        body: data,
        onMessage: (response) => {
          // console.log('接收到消息:', response);
          let result = response.result;
          if (result) {
            this.messages.push(result);
            let output = result.output;
            if (output.text) {
              this.generatedText += output.text
              // this.previewHtml = this.generatedText; //marked.parse(this.generatedText)
            }
          }
        },
        onError: (err) => {
          console.error('SSE 错误:', err);
          this.chatContent(data);
        },
        onClose:() =>{
          console.log('SSE 关闭');
          // if (this.generatedText === '') {
          //   this.chatContent(data);
          // }
          this.loading = false;
        }
      });
    },

    chatContent(data) {
      const loadingInstance = this.$loading({ // 开启加载
        lock: true,
        text: '生成中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      });
      chat(data).then((response) => {
        // console.log(response);
        if (response.code === 200) {
          let result = response.data.result;
          let text = result.output.text;
          if (text) {
            this.generatedText += text
          }
        }
      }).finally(() => {
        this.loading = false;
        loadingInstance.close(); // 关闭加载
      })
    },

    // 保存内容
    saveContent() {
      if (!this.generatedText) {
        this.$message.warning('内容为空，无法保存');
        return;
      }
      if (!this.selectedEmployee || !this.designerEmployee) {
        this.$message.warning('请选择员工');
        return;
      }

      // 调用 API 保存内容
      const data = {
        content: this.generatedText,
        employeeId: this.selectedEmployee,
        designerId: this.designerEmployee,
        prompt: this.prompt
      };

      // 假设 saveContentToServer 是保存内容的 API 方法
      saveContentToServer(data)
        .then(response => {
          if (response.code === 200) {
            this.$message.success('保存成功');
          } else {
            this.$message.error('保存失败: ' + response.msg);
          }
        })
        .catch(error => {
          console.error('保存失败:', error);
          this.$message.error('保存失败，请稍后重试');
        });
    },
    cancel() {
      console.log('取消操作');
    }
  }
};
</script>

<style scoped lang="scss">
.app-container {
  padding: 20px;
}

.generated-content, .preview-effect {
  border: 1px solid #ddd;
  padding: 10px;
  margin-bottom: 20px;
}
</style>
